package vip.xiaomoli.courier.util;

import org.springframework.util.Assert;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CourierUtil {

    public static String getLocalIP() {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            return addr.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static <T> String toString(List<T> list) {
        StringBuilder sb = new StringBuilder();
        for (T t : list) {
            sb.append(t.toString()).append(", ");
        }
        return sb.substring(0, sb.length()-2);
    }

    public static Date addSeconds(final Date date, final int amount) {
        return add(date, Calendar.SECOND, amount);
    }

    public static Date addDays(final Date date, final int amount) {
        return add(date, Calendar.DATE, amount);
    }

    public static Date add(final Date date, final int calendarField, final int amount) {
        Assert.notNull(date, "The date must not be null");
        final Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

    public static int getCurrentSecondInHour() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.SECOND);
    }

    public static int getSeconds(Date date1, Date date2) {
        long seconds = (date1.getTime() - date2.getTime()) / 1000;
        return (int) seconds;
    }

    public static void main(String[] args) {
        Date date = new Date(1549983089000L);
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
    }

}
